package com.orderplus.opshop.core.proxy;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class SQLiteJDBC {

    public static Connection connection() {
        Connection c = null;
        try {
            Class.forName("org.sqlite.JDBC");
            c = DriverManager.getConnection("jdbc:sqlite:spider.db");
        } catch ( Exception e ) {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            System.exit(0);
        }
        System.out.println("Opened database successfully");
        return c;
    }

    public static boolean INSERT(String sql){
        Connection conn = connection();
        try {
            Statement stmt = conn.createStatement();
            int i = stmt.executeUpdate(sql);
            stmt.close();
            conn.close();
            if(i > 0){
                return true;
            }
        } catch ( Exception e ) {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            return false;
        }
        return false;
    }

    public static ResultSet SELECT(String sql){
        Connection conn = connection();
        try {
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            return rs;
        } catch ( Exception e ) {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
        }
        return null;
    }

    public static void main(String[] args) {
        INSERT("INSERT INTO proxy_ip_list (ip, port, type) VALUES('127.0.0.1','1080','http')");
        try {
            ResultSet rs = SELECT("SELECT * FROM proxy_ip_list");
            while ( rs.next() ) {
                System.out.println( "ip = " + rs.getString("ip") );
            }
            rs.close();
        } catch ( Exception e ) {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
        }
    }

}
